#include<stdio.h>
#include<stdlib.h>
struct TreeNode {
    int val;
    struct TreeNode* left;
    struct TreeNode* right;
    
};
typedef struct TreeNode TreeNode;
void mklist(TreeNode* root, TreeNode** list)
{
    if (root == NULL)
        return;
    TreeNode* new = (TreeNode*)malloc(sizeof(TreeNode));
    new->val = root->val;
    new->left = NULL;
    new->right = NULL;
    (*list)->right = new;
    (*list) = (*list)->right;
    mklist(root->left, list);
    mklist(root->right, list);
    return;
}
void flatten(struct TreeNode* root) {
    if (root == NULL)
        return;
    TreeNode** listhead = (TreeNode**)malloc(sizeof(TreeNode));
    TreeNode* _listhead = (TreeNode*)malloc(sizeof(TreeNode));
    TreeNode* list = _listhead;
    _listhead->val = -1;
    _listhead->left = NULL;
    _listhead->right = NULL;
    listhead = &_listhead;
    mklist(root, listhead);
    root->left = NULL;
    root->right = list->right->right;
    return;
}
int main()
{
    TreeNode* n1 = (TreeNode*)malloc(sizeof(TreeNode));
    n1->val = 1;
    n1->left = NULL;
    n1->right = NULL;
    TreeNode* n2 = (TreeNode*)malloc(sizeof(TreeNode));
    n2->val =2 ;
    n2->left = NULL;
    n2->right = NULL; 
    TreeNode* n3 = (TreeNode*)malloc(sizeof(TreeNode));
    n3->val = 3;
    n3->left = NULL;
    n3->right = NULL; 
    TreeNode* n4 = (TreeNode*)malloc(sizeof(TreeNode));
    n4->val = 4;
    n4->left = NULL;
    n4->right = NULL; 
    TreeNode* n5 = (TreeNode*)malloc(sizeof(TreeNode));
    n5->val = 5;
    n5->left = NULL;
    n5->right = NULL;
    TreeNode* n6 = (TreeNode*)malloc(sizeof(TreeNode));
    n6->val = 6;
    n6->left = NULL;
    n6->right = NULL;
    n1->left = n2;
    n1->right = n5;
    n2->left = n3;
    n2->right = n4;
    n5->right = n6;
    flatten(n1);
 	return 0;
}